<template>
  <el-dialog
    title="新增优惠券"
    :visible.sync="dialogVisible"
    width="800px"
    :before-close="beforeCloseHandle"
    append-to-body
  >
    <div class="content">
      <el-form
        :model="couponCreateForm"
        :rules="couponCreateRules"
        ref="couponCreateFormRef"
        class="couponCreateForm"
      >
        <el-form-item label="有效时间" prop="effectiveType">
          <el-radio-group v-model="couponCreateForm.effectiveType">
            <el-radio :label="0">固定时间</el-radio>
            <el-radio :label="1">领券立即生效</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="couponTime" v-if="couponCreateForm.effectiveType === 0">
          <el-form-item prop="startTime">
            <el-date-picker
              v-model="couponCreateForm.startTime"
              format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="开始日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item prop="endTime" class="couponEndTime">
            <el-date-picker
              v-model="couponCreateForm.endTime"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </div>
        <el-form-item
          prop="effectiveDays"
          v-if="couponCreateForm.effectiveType === 1"
        >
          <span
            >领券当日起
            <el-input-number
              :min="1"
              step-strictly
              :step="1"
              :controls="false"
              v-model="couponCreateForm.effectiveDays"
              style="width: 150px"
            />
            天内可用
          </span>
        </el-form-item>
        <el-form-item label="活动规则">
          <CouponRuleForm
            @update="couponListHandle"
            ref="CouponRuleFormRef"
          ></CouponRuleForm>
        </el-form-item>
        <el-form-item label="商品选择" prop="actRules">
          <ApointGoods
            style="padding-left: 80px"
            ref="apointComp"
            :actType="actType"
            :content="couponContent"
          />
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog--footer">
      <el-button @click="closeHandle">取 消</el-button>
      <el-button type="primary" @click="confirmClickHandle">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script lang="ts">
import {
  Component,
  Emit,
  PropSync,
  Ref,
  Vue,
  Watch,
} from "vue-property-decorator";
import { GiveCoupon } from "../../formModel/GiveCoupon";
import ApointGoods from "@/views/marketing/common/ApointGoods.vue";
import CouponRuleForm from "@/views/customer/list/components/dialog/CouponRuleForm.vue";

@Component({
  components: {
    ApointGoods,
    CouponRuleForm,
  },
})
export default class CreateCoupons extends Vue {
  @PropSync("visible", {
    type: Boolean,
    default: false,
  })
  dialogVisible: boolean;

  @Ref() readonly couponCreateFormRef: HTMLFormElement;

  @Ref() readonly CouponRuleFormRef: HTMLFormElement;

  @Ref()
  readonly apointComp: HTMLFormElement;

  actType = "AddActivity";

  /** 优惠券信息 */
  couponContent = {};

  /** 用户输入表单数据 */
  couponCreateForm = {
    effectiveType: 0,
    couponList: [
      {
        couponType: "",
        discount: "",
        conditionAmount: "",
        discountAmount: "",
      },
    ],
    startTime: "",
    endTime: "",
    effectiveDays: 1,
    productType: 0,
    couponProducts: [],
  };

  // 优惠券规则校验结果
  checked = false;

  pickerOptions = {
    disabledDate(time) {
      const now = new Date(new Date().toLocaleDateString()).getTime();
      return time.getTime() < now;
    },
  };

  couponCreateRules: any = {
    effectiveType: [
      { required: true, message: "请选择有效时间", trigger: "change" },
    ],
    startTime: [
      { required: true, message: "请选择开始时间", trigger: "change" },
    ],
    endTime: [
      { required: true, validator: this.validatePass, trigger: "change" },
    ],
    effectiveDays: [
      { required: true, validator: this.validateday, trigger: "change" },
    ],
    productType: [
      { required: true, message: "请选择适用商品", trigger: "change" },
    ],
  };

  @Watch("dialogVisible")
  handleVisibleChange(v) {
    if (v) {
      this.couponCreateForm = {
        effectiveType: 0,
        couponList: [
          {
            couponType: "",
            discount: "",
            conditionAmount: "",
            discountAmount: "",
          },
        ],
        startTime: "",
        endTime: "",
        effectiveDays: null,
        productType: 0,
        couponProducts: [],
      };
    } else {
      this.CouponRuleFormRef.clearValidate();
    }
  }

  couponListHandle(couponList) {
    this.couponCreateForm.couponList = couponList;
  }

  /**
   * 限制只能输入正整数
   */
  proving(value) {
    let values = value;
    values = value.replace(/[^\.\d]/g, "");
    values = value.replace(".", "");
    return values;
  }

  /**
   * 对整个表单进行校验
   */
  formValidate() {
    return this.couponCreateFormRef.validate();
  }

  async confirmClickHandle() {
    try {
      await this.formValidate();
      await this.CouponRuleFormRef.validate();
      this.emitCreateCoupons();
      this.dialogVisible = false;
      this.apointComp.pointGoodsList = [];
      this.apointComp.goodRadio = 0;
    } catch (e) {
      console.log(e);
    }
  }

  /**
   * 触发更新菜单事件
   */
  @Emit("createCoupons")
  emitCreateCoupons() {
    const couponCreateForm = this.couponCreateForm;
    return couponCreateForm.couponList.map((item) => {
      const coupon = new GiveCoupon();
      coupon.effectiveType = couponCreateForm.effectiveType;
      coupon.effectiveDays = couponCreateForm.effectiveDays;
      coupon.startTime = couponCreateForm.startTime;
      coupon.endTime = couponCreateForm.endTime.replace("00:00:00", "23:59:59");
      Object.assign(coupon, item);
      coupon.productType = this.apointComp.goodRadio;
      coupon.couponProducts = this.apointComp.pointGoodsList.map((item) => {
        return {
          productId: item.id,
        };
      });
      return coupon;
    });
  }

  validatePass(rule, value, callback) {
    if (!this.couponCreateForm.startTime) {
      callback(new Error("请选择开始时间"));
    }
    if (!value) {
      callback(new Error("请选择结束时间"));
    }
    const start = new Date(this.couponCreateForm.startTime).getTime();
    const end = new Date(value).getTime();
    if (start > end) {
      callback(new Error("结束时间不能小于开始时间"));
    }
    callback();
  }

  validateday(rule, value, callback) {
    const regs = /^[+]{0,1}(\d+)$/;
    if (!regs.test(value)) {
      callback(new Error("有效期请输入整数"));
    } else if (value <= 0) {
      callback(new Error("有效期不能小于1"));
    } else {
      callback();
    }
  }

  /**
   * 关闭弹窗
   */
  async closeHandle() {
    try {
      const result = await this.confirmHandle();
      if (result === "confirm") {
        this.dialogVisible = false;
      }
    } catch (e) {
      console.log(e);
    }
  }

  async beforeCloseHandle(done) {
    try {
      const result = await this.confirmHandle();
      if (result === "confirm") {
        done();
      }
    } catch (e) {
      console.log(e);
    }
  }

  /**
   * 关闭确认
   */
  async confirmHandle() {
    return await this.$confirm(
      "确定退出创建优惠券页面？退出后，赠送优惠券信息将不保留！",
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );
  }
}
</script>

<style scoped lang="scss">
.couponCreateForm {
  margin-left: 40px;

  .couponTime {
    display: flex;
    justify-content: flex-start;

    /deep/ .couponEndTime .el-form-item__content {
      margin-left: 40px;
    }
  }
}
</style>
